#include "savegroundlongwv.h"

SaveGroundLongWV::SaveGroundLongWV(int width, int height, QObject *parent) : SaveBase(parent)
{
    m_hasHead = false;
    m_totalPackets = height;
    m_width = width;
    m_height = height;
    m_bytes = m_height * m_width * 2;
}

void SaveGroundLongWV::onWorking(const QString ip, const quint16 port, const QByteArray arr)
{
    if(!m_saveStatues || arr.isEmpty() || ip != m_srcIP) {
        //qDebug() << "数据未经过判断条件！" << "arr is Empty:" << arr.isEmpty() << "ip == m_srcIP" << (ip == m_srcIP);
        //qDebug() << "ip = " << ip << "m_srcIp = " << m_srcIP;
        return;
    }

//    // 每收到一行数据，帧数加1
//    m_TimeCount++;

//    // 检查是否已经超过1秒，计算帧率
//    if (m_fpsTimer.elapsed() >= 1000) {
//        m_currentFps = m_TimeCount * 1000.0 / m_fpsTimer.elapsed();
//        qDebug() << "存储端收到的帧率为:" << QString::number(m_currentFps / m_height + 1, 'f', 1) << "FPS";

//        // 重置计时器和计数器
//        m_fpsTimer.restart();
//        m_TimeCount = 0;
//    }

    if(arr.size() < 8) {
        return;
    }

    if (static_cast<quint8>(arr[0]) == 0xF0 && static_cast<quint8>(arr[1]) == 0x5A &&
            static_cast<quint8>(arr[2]) == 0xA5 && static_cast<quint8>(arr[3]) == 0x0F) {

            // 验证第一个分片是否为正确字节
        if (arr.size() != m_width * 2 + 8) {
            qWarning() << "第一帧必须是648bytes" << arr.size();
            return;
        }

        frame.width = (static_cast<quint8>(arr[4]) << 8) | static_cast<quint8>(arr[5]);
        frame.height = (static_cast<quint8>(arr[6]) << 8) | static_cast<quint8>(arr[7]);

        m_hasHead = true;

        //如果第一帧收到的时候有内容，则认为之前的数据丢包了，不完整，直接丢弃
        frame.data = arr;
        m_receivedPackets = 1;
    } else {
        // 非首包处理：需先收到帧头且总包数有效
        if (m_receivedPackets == 0 || !m_hasHead) {
            return;
        }
        // 验证后续分片是否为正确字节
        if (arr.size() != m_width * 2) {
            return;
        }

        frame.data.append(arr);
        m_receivedPackets++;
    }

    // 检查帧是否完整
    if (m_receivedPackets >= m_totalPackets) {
        //qDebug() << "data.size:" << data.size();
        // 验证帧头
        if (static_cast<quint8>(frame.data[0]) != 0xF0 ||
            static_cast<quint8>(frame.data[1]) != 0x5A ||
            static_cast<quint8>(frame.data[2]) != 0xA5 ||
            static_cast<quint8>(frame.data[3]) != 0x0F ||
            frame.data.size() != m_bytes + 8) {
            qWarning() << "Invalid frame";
            return;
        }

        //测试，显示图像
        //emit sigToShowImg(m_srcIP, m_bindPort, imageData);

        // 保存RAW图像,提取图像数据 (跳过8字节帧头)
        m_hasHead = false;
        saveRawImage(frame.data.mid(8));
    }
}

bool SaveGroundLongWV::saveRawImage(const QByteArray &imageData) {

    if (!checkAndSwitchDisk()) {
        return false; // 所有磁盘不可用，直接返回
    }

    // 构造完整文件路径：磁盘路径/基础路径/相机名称/文件名
    QString currentDisk = m_diskPaths[m_currentDiskIndex];
    QString fullDir = QString("%1/%2/%3").arg(currentDisk).arg(m_fileSavePath).arg(m_videoName);
    QDir dir(fullDir);
    if(m_creatDir) {
        if (!dir.exists() && !dir.mkpath(".")) { // 确保目录存在
            qDebug() << "无法创建目录:" << fullDir;
            return false;
        }
        m_creatDir = false;
    }

    // 生成文件名（包含时间戳）
    m_fileStartTime = QDateTime::currentDateTime();
    QString fileName = QString("%1/%2_%3.raw")
            .arg(fullDir)
            .arg(m_desc)
            .arg(m_fileStartTime.toString("yyyy-MM-dd_hh-mm-ss-zzz"));

    m_file.setFileName(fileName);
    if (!m_file.open(QIODevice::WriteOnly)) {
        qDebug() << "无法创建文件:" << fileName << "错误:" << m_file.errorString();
        return false;
    }

    //写入raw
    m_file.write(imageData);
    m_file.close();
    qDebug() << "完成一张存储";
    return true;
}
